package edu.hawaii.webspider;

import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Test class for WebSpider and WebSpiderFormatter.
 * 
 * @author Lisa Chen
 * 
 */
public class TestWebSpider {

  /** Test url to crawl. */
  private final String testUrl = "http://www2.hawaii.edu/~lisachen";
  /** Test log message. */
  private final String testMessage = "Test log message.";
  /** Test formatted date. */
  private final SimpleDateFormat testFormattedDate = new SimpleDateFormat("HH:mm:ss", Locale.US);
  /** Test short formatted date as string. */
  private final String shortDate = testFormattedDate.format(new Date());

  /**
   * Test getNumLinks in WebSpider.
   * 
   * @throws Exception
   *             Not able to access start url.
   */
  @Test
  public void testGetNumLinks() throws Exception {

    try {
      WebSpider example = new WebSpider(this.testUrl);
      assertEquals("Number of links on " + this.testUrl, 7, example.getNumLinks());
    }
    catch (Exception e) {
      fail("Trouble accessing " + this.testUrl + ", error: " + e);
    }
  }

  /**
   * Test getNumLinks in first N pages (nNumPages) of a URL (testUrl).
   * 
   * @throws Exception
   *             Not able to access start url.
   */
  @Test
  public void testNumLinksNPages() throws Exception {
    // test crawl on first 10 pages
    int nNumPages = 2;

    try {
      WebSpider example = new WebSpider(this.testUrl, nNumPages);
      assertEquals("Testing number of links on " + this.testUrl + " crawled across " + nNumPages
          + " pages.", 17, example.getNumLinks(nNumPages));
    }
    catch (RuntimeException e) {
      fail("Trouble accessing " + this.testUrl + e);
    }
  }

  /**
   * Test overrided format method in WebSpiderFormatter class.
   */
  @Test
  public void testFormatter() {
    // create a test formatter
    WebSpiderFormatter testFormatter = new WebSpiderFormatter();
    // create a record for formatting
    LogRecord testRecord = new LogRecord(Level.INFO, this.testMessage);

    assertEquals("Testing Formatter: ", this.shortDate + " " + this.testMessage + "\r\n",
        testFormatter.format(testRecord));
  }

  /**
   * Test writeToLog method in WebSpider.
   */
  @Test
  public void testWriteToLogs() {
    WebSpider example = new WebSpider(this.testUrl);
    assertEquals("Testing log writer: ", true, example.writeToLog(this.testMessage));

  }
}
